package helperx

import (
	"fmt"
	"strings"

	"github.com/shopspring/decimal"
)

// CentToYuan 分转元
func CentToYuan(cent uint64) string {
	c := decimal.NewFromInt(int64(cent))
	return c.DivRound(decimal.NewFromInt(100), 2).String()
}

// YuanToCent 元转分
func YuanToCent(yuan string) (uint64, error) {
	y, err := decimal.NewFromString(yuan)
	if err != nil {
		return 0, err
	}
	return uint64(y.Mul(decimal.NewFromInt(100)).IntPart()), nil
}

// NiceRate 格式化百分比 0.001 -> 0.1%
func NiceRate(aPercentage float64) string {
	aPercentage = aPercentage * 100
	aFormattedPercentage := fmt.Sprintf("%.6f", aPercentage)
	aTrimmedPercentage := strings.TrimRight(aFormattedPercentage, "0")
	if strings.HasSuffix(aTrimmedPercentage, ".") {
		aTrimmedPercentage = aTrimmedPercentage[:len(aTrimmedPercentage)-1]
	}
	return aTrimmedPercentage + "%"
}
